package org.raymond.iworks.study.mq.rabbitmq.classic.pubsub;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Random;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class ReceiveLogs {

    public static void main(String[] args) throws Exception {
        String EXCHANGE_NAME = EmitLog.EXCHANGE_NAME;
        Connection conn = EmitLog.connection();
        Channel channel = conn.createChannel();



        // 如果队列还没有绑定到交换器时就已经发送了消息,此时没有消费者在监听,
        // 那么消息将安全的丢失.
        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
        // 声明队列没有任何参数时,创建一个非持久,独占, 自动删除(当所有消费者都断开连接时)的队列
        // 独占队列只能由声明它的链接使用,独占队列在声明它的链接被关闭或消失(底层tcp连接丢失)时删除.
        // 因此,独占队列只适用于特定客户端的瞬态
        String queueRandomName = channel.queueDeclare().getQueue();
        // fanout中忽略routingKey
        channel.queueBind(queueRandomName, EXCHANGE_NAME, "");
        log.info("[*] Waiting for message");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            log.info(" [x] Received {}", message);
            try{
                doWork(message);
            }catch (InterruptedException e){
                log.error("{}: {} will intterrupt.", e.getMessage(), Thread.currentThread().getName());
                Thread.currentThread().interrupt();
            }finally {
                // fanout下一个消费者拒绝另一个消费者确认,无特殊情况
                Random random = new Random();
                long deliveryTag = delivery.getEnvelope().getDeliveryTag();
                int next = random.nextInt(100); // 生成一个0-99的数
                log.info(" [x] Done. next:{}, deliveryTag:{}", next, deliveryTag);
                if(next>51) {
                    // 手动确认时,如果没有进行确认,临时队列里的消息依然存在,但不会转发给其他消费者,因为其他消费者都已经接受过一次消息了
                    channel.basicAck(deliveryTag, false);
                }else{
                    channel.basicNack(deliveryTag, false,true);
                }
            }
        };

        boolean autoAck = false;
        String cnt = channel.basicConsume(queueRandomName, autoAck, deliverCallback, consumerTag->{});
        log.info("consumerTag: {}", cnt);
    }

    private static void doWork(String task) throws InterruptedException {
        if(task.startsWith("interrupted")){
            Thread.currentThread().interrupt();
        }
        for (char ch: task.toCharArray()){
            if(ch=='.') Thread.sleep(1000);
        }
    }
}
